<template>
  <view class="invite-container">
    <!-- 头部背景 -->
    <view class="invite-header">
      <view class="header-bg">
        <view class="header-content">
          <view class="invite-title">邀请好友，共享收益</view>
          <view class="invite-subtitle">邀请越多，奖励越丰厚</view>
        </view>
      </view>
    </view>
    
    <!-- 邀请码卡片 -->
    <view class="invite-code-card">
      <view class="card-header">
        <view class="card-title">我的邀请码</view>
        <view class="card-subtitle">分享给好友即可获得奖励</view>
      </view>
      
      <view class="invite-code-display">
        <view class="code-text">{{ inviteCode || '加载中...' }}</view>
        <button 
          class="copy-btn" 
          @click="copyInviteCode"
          :disabled="!inviteCode"
        >
          复制
        </button>
      </view>
      
      <!-- 二维码 -->
      <view class="qr-code-section" v-if="qrCodeDataUrl">
        <view class="qr-title">扫码邀请</view>
        <image 
          :src="qrCodeDataUrl" 
          class="qr-code-image"
          mode="aspectFit"
        />
        <view class="qr-tip">长按保存二维码分享给好友</view>
      </view>
    </view>
    
    <!-- 奖励规则 -->
    <view class="reward-rules-card">
      <view class="rules-title">奖励规则</view>
      <view class="rules-list">
        <view class="rule-item">
          <view class="rule-icon">🎁</view>
          <view class="rule-content">
            <view class="rule-title">注册奖励</view>
            <view class="rule-desc">好友注册成功，双方各得50积分</view>
          </view>
        </view>
        
        <view class="rule-item">
          <view class="rule-icon">💰</view>
          <view class="rule-content">
            <view class="rule-title">消费奖励</view>
            <view class="rule-desc">好友首次消费，您获得消费金额10%的积分奖励</view>
          </view>
        </view>
        
        <view class="rule-item">
          <view class="rule-icon">👑</view>
          <view class="rule-content">
            <view class="rule-title">等级特权</view>
            <view class="rule-desc">邀请满10人升级VIP，享受更多特权</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 邀请统计 -->
    <view class="invite-stats-card">
      <view class="stats-title">我的邀请统计</view>
      <view class="stats-grid">
        <view class="stat-item">
          <view class="stat-value">{{ stats.totalInvites || 0 }}</view>
          <view class="stat-label">累计邀请</view>
        </view>
        
        <view class="stat-item">
          <view class="stat-value">{{ stats.totalRewards || 0 }}</view>
          <view class="stat-label">总奖励积分</view>
        </view>
        
        <view class="stat-item">
          <view class="stat-value">{{ stats.monthlyInvites || 0 }}</view>
          <view class="stat-label">本月邀请</view>
        </view>
        
        <view class="stat-item">
          <view class="stat-value">{{ stats.completionRate || 0 }}%</view>
          <view class="stat-label">转化率</view>
        </view>
      </view>
    </view>
    
    <!-- 邀请记录 -->
    <view class="invite-records-card" v-if="stats.recentInvites && stats.recentInvites.length > 0">
      <view class="records-header">
        <view class="records-title">最近邀请</view>
        <view class="view-all-btn" @click="viewAllInvites">查看全部</view>
      </view>
      
      <view class="records-list">
        <view 
          v-for="(invite, index) in stats.recentInvites" 
          :key="index"
          class="record-item"
        >
          <view class="record-avatar">
            <image 
              :src="invite.invitee.avatar || '/static/icons/default-avatar.png'" 
              class="avatar-image"
            />
          </view>
          
          <view class="record-info">
            <view class="record-name">{{ invite.invitee.nickname || '新用户' }}</view>
            <view class="record-time">{{ formatTime(invite.registerTime) }}</view>
          </view>
          
          <view class="record-status">
            <view 
              :class="['status-badge', invite.firstConsumeTime ? 'completed' : 'pending']"
            >
              {{ invite.firstConsumeTime ? '已消费' : '待消费' }}
            </view>
            <view class="record-reward">+{{ invite.rewardPoints }}积分</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 分享按钮 -->
    <view class="share-actions">
      <button class="share-btn primary" @click="shareToWechat">
        <view class="btn-icon">📱</view>
        <view class="btn-text">微信分享</view>
      </button>
      
      <button class="share-btn secondary" @click="shareToFriends">
        <view class="btn-icon">👥</view>
        <view class="btn-text">分享给朋友</view>
      </button>
    </view>
    
    <!-- 排行榜入口 -->
    <view class="ranking-entry" @click="viewRanking">
      <view class="ranking-icon">🏆</view>
      <view class="ranking-text">查看邀请排行榜</view>
      <view class="ranking-arrow">></view>
    </view>
  </view>
</template>

<script>
import { 
  getInviteShareInfo, 
  getInviteStats,
  generateInviteQRCode 
} from '@/api/invitations.js'

export default {
  name: 'InvitePage',
  
  data() {
    return {
      inviteCode: '',
      qrCodeDataUrl: '',
      shareUrl: '',
      shareTitle: '',
      shareDesc: '',
      stats: {
        totalInvites: 0,
        totalRewards: 0,
        monthlyInvites: 0,
        completionRate: 0,
        recentInvites: []
      },
      isLoading: false
    }
  },
  
  onLoad() {
    this.loadInviteInfo()
  },
  
  onShow() {
    // 页面显示时刷新统计数据
    this.loadStats()
  },
  
  onPullDownRefresh() {
    this.loadInviteInfo().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  
  methods: {
    /**
     * 加载邀请信息
     */
    async loadInviteInfo() {
      if (this.isLoading) return
      
      this.isLoading = true
      
      try {
        const result = await getInviteShareInfo()
        
        if (result.success) {
          const data = result.data
          this.inviteCode = data.inviteCode
          this.qrCodeDataUrl = data.qrCodeDataUrl
          this.shareUrl = data.shareUrl
          this.shareTitle = data.shareTitle
          this.shareDesc = data.shareDesc
          this.stats = data.stats
        } else {
          this.showError(result.message || '加载邀请信息失败')
        }
      } catch (error) {
        console.error('加载邀请信息失败:', error)
        this.showError('加载邀请信息失败')
      } finally {
        this.isLoading = false
      }
    },
    
    /**
     * 加载统计数据
     */
    async loadStats() {
      try {
        const result = await getInviteStats()
        
        if (result.success) {
          this.stats = result.data
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    },
    
    /**
     * 复制邀请码
     */
    copyInviteCode() {
      if (!this.inviteCode) {
        this.showError('邀请码不存在')
        return
      }
      
      // #ifdef H5
      if (navigator.clipboard) {
        navigator.clipboard.writeText(this.inviteCode).then(() => {
          this.showSuccess('邀请码已复制到剪贴板')
        }).catch(() => {
          this.fallbackCopy(this.inviteCode)
        })
      } else {
        this.fallbackCopy(this.inviteCode)
      }
      // #endif
      
      // #ifdef MP-WEIXIN
      uni.setClipboardData({
        data: this.inviteCode,
        success: () => {
          this.showSuccess('邀请码已复制到剪贴板')
        },
        fail: () => {
          this.showError('复制失败，请手动复制')
        }
      })
      // #endif
      
      // #ifdef APP-PLUS
      uni.setClipboardData({
        data: this.inviteCode,
        success: () => {
          this.showSuccess('邀请码已复制到剪贴板')
        }
      })
      // #endif
    },
    
    /**
     * 降级复制方法
     */
    fallbackCopy(text) {
      const textArea = document.createElement('textarea')
      textArea.value = text
      document.body.appendChild(textArea)
      textArea.select()
      
      try {
        document.execCommand('copy')
        this.showSuccess('邀请码已复制到剪贴板')
      } catch (err) {
        this.showError('复制失败，请手动复制')
      }
      
      document.body.removeChild(textArea)
    },
    
    /**
     * 微信分享
     */
    shareToWechat() {
      // #ifdef MP-WEIXIN
      uni.showShareMenu({
        withShareTicket: true,
        success: () => {
          console.log('显示分享菜单成功')
        }
      })
      // #endif
      
      // #ifdef H5
      if (this.isWechat()) {
        // 微信浏览器环境
        this.showTip('请点击右上角分享按钮')
      } else {
        // 其他浏览器
        this.shareToFriends()
      }
      // #endif
      
      // #ifdef APP-PLUS
      this.shareToFriends()
      // #endif
    },
    
    /**
     * 分享给朋友
     */
    shareToFriends() {
      const shareContent = `${this.shareTitle}\n\n${this.shareDesc}\n\n邀请链接：${this.shareUrl}`
      
      uni.showActionSheet({
        itemList: ['复制分享内容', '保存二维码'],
        success: (res) => {
          if (res.tapIndex === 0) {
            // 复制分享内容
            this.copyText(shareContent)
          } else if (res.tapIndex === 1) {
            // 保存二维码
            this.saveQRCode()
          }
        }
      })
    },
    
    /**
     * 复制文本
     */
    copyText(text) {
      // #ifdef H5
      if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
          this.showSuccess('分享内容已复制')
        })
      } else {
        this.fallbackCopy(text)
      }
      // #endif
      
      // #ifndef H5
      uni.setClipboardData({
        data: text,
        success: () => {
          this.showSuccess('分享内容已复制')
        }
      })
      // #endif
    },
    
    /**
     * 保存二维码
     */
    saveQRCode() {
      if (!this.qrCodeDataUrl) {
        this.showError('二维码不存在')
        return
      }
      
      // #ifdef MP-WEIXIN
      uni.saveImageToPhotosAlbum({
        filePath: this.qrCodeDataUrl,
        success: () => {
          this.showSuccess('二维码已保存到相册')
        },
        fail: () => {
          this.showError('保存失败，请检查相册权限')
        }
      })
      // #endif
      
      // #ifdef H5
      const link = document.createElement('a')
      link.download = 'invite-qrcode.png'
      link.href = this.qrCodeDataUrl
      link.click()
      this.showSuccess('二维码已下载')
      // #endif
      
      // #ifdef APP-PLUS
      // APP环境下的保存逻辑
      this.showTip('长按二维码保存到相册')
      // #endif
    },
    
    /**
     * 查看全部邀请
     */
    viewAllInvites() {
      uni.navigateTo({
        url: '/pages/invite/details'
      })
    },
    
    /**
     * 查看排行榜
     */
    viewRanking() {
      uni.navigateTo({
        url: '/pages/invite/ranking'
      })
    },
    
    /**
     * 格式化时间
     */
    formatTime(time) {
      if (!time) return ''
      
      const date = new Date(time)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return Math.floor(diff / 60000) + '分钟前'
      } else if (diff < 86400000) { // 1天内
        return Math.floor(diff / 3600000) + '小时前'
      } else if (diff < 2592000000) { // 30天内
        return Math.floor(diff / 86400000) + '天前'
      } else {
        return date.toLocaleDateString()
      }
    },
    
    /**
     * 检查是否在微信环境
     */
    isWechat() {
      return /micromessenger/i.test(navigator.userAgent)
    },
    
    /**
     * 显示成功提示
     */
    showSuccess(message) {
      uni.showToast({
        title: message,
        icon: 'success'
      })
    },
    
    /**
     * 显示错误提示
     */
    showError(message) {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    },
    
    /**
     * 显示提示
     */
    showTip(message) {
      uni.showModal({
        title: '提示',
        content: message,
        showCancel: false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.invite-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #667eea 0%, #764ba2 100%);
  padding-bottom: 40rpx;
}

.invite-header {
  padding: 60rpx 40rpx 40rpx;
  text-align: center;
}

.header-content {
  color: white;
}

.invite-title {
  font-size: 48rpx;
  font-weight: bold;
  margin-bottom: 16rpx;
}

.invite-subtitle {
  font-size: 28rpx;
  opacity: 0.9;
}

.invite-code-card,
.reward-rules-card,
.invite-stats-card,
.invite-records-card {
  background: white;
  border-radius: 24rpx;
  margin: 20rpx 30rpx;
  padding: 40rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
  margin-bottom: 40rpx;
}

.card-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.card-subtitle {
  font-size: 26rpx;
  color: #666;
}

.invite-code-display {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9ff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 40rpx;
}

.code-text {
  font-size: 36rpx;
  font-weight: bold;
  color: #667eea;
  letter-spacing: 4rpx;
  margin-right: 20rpx;
}

.copy-btn {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 12rpx;
  padding: 16rpx 32rpx;
  font-size: 28rpx;
  
  &:disabled {
    opacity: 0.6;
  }
}

.qr-code-section {
  text-align: center;
}

.qr-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 24rpx;
}

.qr-code-image {
  width: 300rpx;
  height: 300rpx;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
}

.qr-tip {
  font-size: 24rpx;
  color: #666;
}

.rules-title,
.stats-title,
.records-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 32rpx;
}

.rules-list {
  space-y: 24rpx;
}

.rule-item {
  display: flex;
  align-items: flex-start;
  padding: 20rpx 0;
}

.rule-icon {
  font-size: 32rpx;
  margin-right: 20rpx;
  margin-top: 4rpx;
}

.rule-content {
  flex: 1;
}

.rule-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.rule-desc {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 32rpx;
}

.stat-item {
  text-align: center;
  padding: 24rpx;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 16rpx;
  color: white;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.stat-label {
  font-size: 24rpx;
  opacity: 0.9;
}

.records-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
}

.view-all-btn {
  font-size: 26rpx;
  color: #667eea;
}

.records-list {
  space-y: 20rpx;
}

.record-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.record-avatar {
  margin-right: 20rpx;
}

.avatar-image {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
}

.record-info {
  flex: 1;
}

.record-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 4rpx;
}

.record-time {
  font-size: 24rpx;
  color: #666;
}

.record-status {
  text-align: right;
}

.status-badge {
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  margin-bottom: 4rpx;
  
  &.completed {
    background: #52c41a;
    color: white;
  }
  
  &.pending {
    background: #faad14;
    color: white;
  }
}

.record-reward {
  font-size: 24rpx;
  color: #52c41a;
  font-weight: bold;
}

.share-actions {
  display: flex;
  gap: 20rpx;
  margin: 40rpx 30rpx;
}

.share-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 32rpx 20rpx;
  border-radius: 16rpx;
  border: none;
  
  &.primary {
    background: #52c41a;
    color: white;
  }
  
  &.secondary {
    background: white;
    color: #333;
    border: 2rpx solid #e0e0e0;
  }
}

.btn-icon {
  font-size: 32rpx;
  margin-bottom: 8rpx;
}

.btn-text {
  font-size: 26rpx;
}

.ranking-entry {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 16rpx;
  margin: 20rpx 30rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.ranking-icon {
  font-size: 32rpx;
  margin-right: 20rpx;
}

.ranking-text {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.ranking-arrow {
  font-size: 24rpx;
  color: #666;
}
</style>